﻿Imports System.Threading
Imports System.Threading.Tasks
Imports System.Delegate
Imports IRCTest



Public Class TravianIRC
    Inherits System.Web.UI.Page

    Shared bot As IRCBot
    Shared userInfo(1) As String
    Shared users As New List(Of WpfApplication1.User)
    Dim errorMsg As String = "Verplicht veld !"


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        userInfo = Session("New")
        If (Me.IsPostBack) Then
            WebChat1.UserName = userInfo(0)
            lblError.Text = errorMsg
            listBoxUsers.DataSource = users
            listBoxUsers.DataTextField = "Username"
            listBoxUsers.DataValueField = "Username"
            listBoxUsers.DataBind()
        End If

        If (userInfo(0).Equals("Geoffry")) Then
            btnAdmin.Visible = True
        End If

        If (bot Is Nothing) Then


            listBoxUsers.DataTextField = "Username"

            bot = New IRCTest.IRCBot(userInfo(0), userInfo(1), "#FlamingFalcons", "#FF")

            Dim t As New Task(AddressOf bot.RUN)

            Try
                AddHandler bot.onMessageReceived, New IRCMEvent(AddressOf HandleMessage)
                AddHandler bot.onUserEvent, New IRCTest.IRCUEvent(AddressOf UserAction)
                AddHandler bot.onCommand, New IRCTest.IRCCEvent(AddressOf CommandReceived)
                AddHandler bot.onUserCheck, New IRCTest.IRCListEvent(AddressOf OnUserCheck)
                AddHandler bot.onMessageSend, New IRCTest.BotMessageSend(AddressOf MessageSend)
                'OnPrivMsg / ToBeImplemented 
                AddHandler bot.onKick, New IRCKicked(AddressOf UserKicked)

                t.Start()

            Catch ex As Exception
                'Print de errorboodschap in WebChat
                updateOutput("ErrorMan :", ex.ToString)
            End Try
        End If

    End Sub


    'HandleMessage
    Public Sub HandleMessage(ByVal sender As Object, ByVal e As IRCTest.IRCMessageEvent)
        If (e.Line.Contains(":natar.traviangames.org NOTICE Auth :Welcome to TravianGames!")) Then
            bot.Identify()
            bot.Ask_inv()
            Thread.Sleep(750)

            bot.Join_Chan()
            updateOutput("Logged in", vbCrLf)
        Else
            updateOutput(e.User, e.Message)
        End If
    End Sub

    'UserAction
    Public Sub UserAction(ByVal sender As Object, ByVal e As IRCUserEvent)
        Try
            If (e.Joined) Then
                AddOrUpdateUser(e)
            ElseIf (e.NickChange) Then
                Dim x = users.FindIndex(Function(c As WpfApplication1.User) c.Username.Equals(e.User))
                users(x).Username = e.NewNick
                users(x).GetData(e.NewNick)
            Else
                RemoveChannelOrUser(e)
            End If
        Catch ex As Exception
            updateOutput("Exception : ", ex.Message)
        End Try


    End Sub

    'MessageSend
    Private Sub MessageSend(ByVal IRCBotInstance As Object, ByVal e As MessageSendEvent)
        updateOutput(bot.Nick, e.Message)
    End Sub

    'CommandReceived
    Private Sub CommandReceived(ByVal sender As Object, ByVal e As IRCCommandEvent)

        Dim s As WpfApplication1.User = users.SingleOrDefault(Function(x As WpfApplication1.User) x.Username.Equals(e.User))
        If (s.ValidUser) Then
            bot.Actions.Handle(e.CommandName, s, e.Channel, e.Parameters)
        Else
            bot.Actions.Send_Message2("This privilege is given to our members only :-)", e.User)
        End If

    End Sub

    'OnUserCheck
    Private Sub OnUserCheck(ByVal IRCBotInstance As Object, ByVal listEvent As IRCUserList)

        Dim d = From user In listEvent.Users
                Select user

        For Each user As String In d
            Dim member = (From person In users Where (person IsNot Nothing) AndAlso (person.Username.Equals(user))
                          Select person)
            Dim count As Integer = member.Count
            If (count = 0 AndAlso Not user.Equals(String.Empty)) Then
                Dim u As New WpfApplication1.User(user, listEvent.Channel)
                users.Add(u)
            ElseIf (count = 1) Then
                Dim index As Integer = users.FindIndex(Function(x As WpfApplication1.User) x.Equals(member.FirstOrDefault))
                users(index).addChannel(listEvent.Channel)
            End If

            If (user.Equals("Falco") AndAlso Not IsNothing(listBoxUsers.Items.FindByText(listEvent.Channel))) Then
                listBoxUsers.Items.Add(listEvent.Channel)
                listBoxUsers.SelectedIndex = listBoxUsers.Items.Count - 1

            End If

        Next
        listBoxUsers.DataSource = users
        listBoxUsers.DataBind()
    End Sub

    'RemoveChannelOrUser
    Private Sub RemoveChannelOrUser(ByVal e As IRCBasicEvent)

        Dim user = From person In users Where person.Username.Equals(e.User)
                   Select person

        If (user.Count > 0 AndAlso Not e.User.Equals("")) Then
            Dim index = users.FindIndex(Function(m As WpfApplication1.User) m.Username.Equals(e.User))
            If (users(index).isInChannel(e.Channel) AndAlso Not users(index).isOnlyChannel(e.Channel)) Then
                users(index).removeChannel(e.Channel)
            Else
                users.RemoveAt(index)
            End If
        End If
        listBoxUsers.DataSource = users
        listBoxUsers.DataBind()
    End Sub

    'AddOrUpdateUser
    Private Sub AddOrUpdateUser(ByVal e As IRCBasicEvent)

        If (Not e.User.Equals(String.Empty)) Then
            Dim user = From person In users Where person.Username.Equals(e.User)
                       Select person

            If (user.Count() = 0) Then
                Dim u As WpfApplication1.User = New WpfApplication1.User(e.User, e.Channel)
                users.Add(u)
            End If
            If (user.Count() = 1) Then
                Dim index As Integer = users.FindIndex(Function(u As WpfApplication1.User) u.Equals(user.FirstOrDefault()))
                users(index).addChannel(e.Channel)
            End If
        End If
        listBoxUsers.DataSource = users
        listBoxUsers.DataBind()

    End Sub

    'UserKicked
    Private Sub UserKicked(ByVal IRCBotInstance As Object, ByVal e As IRCKick)
        RemoveChannelOrUser(e)
    End Sub

    'updateOutput
    Private Sub updateOutput(ByVal user As String, ByVal msg As String)
        WebChat1.UserName = user
        If (Not WebChat1.UserName.Equals(userInfo(0))) Then
            WebChat1.RaiseCallbackEvent("999||" & msg)
        End If
    End Sub

    Private Sub SendMsgToBot(ByRef msg As String) Handles WebChat1.Chatter
        If (WebChat1.UserName.Equals(userInfo(0))) Then
            bot.Actions.Send_Message2(msg, bot.Actions.Channel2)
        End If

    End Sub

    Protected Sub btnKick_Click(sender As Object, e As EventArgs) Handles btnKick.Click
        lblError.Visible = False
        If (Not txtActiePers.Text = String.Empty) Then
            bot.Actions.Kick(txtActiePers.Text, bot.Actions.Channel, txtReden.Text)
        Else
            lblError.Visible = True
        End If
    End Sub

    Protected Sub btnNotice_Click(sender As Object, e As EventArgs) Handles btnNotice.Click
        lblError.Visible = False
        If (Not txtReden.Text = String.Empty) Then
            bot.Actions.Notice(txtReden.Text, txtActiePers.Text)
        Else
            lblError.Visible = True
        End If
    End Sub

    Protected Sub btnPerform_Click(sender As Object, e As EventArgs) Handles btnPerform.Click
        lblError.Visible = False
        If (Not txtReden.Text = String.Empty) Then
            bot.Actions.Emote(txtReden.Text, txtActiePers.Text)
        Else
            lblError.Visible = True
        End If
    End Sub

    Protected Sub btnSlap_Click(sender As Object, e As EventArgs) Handles btnSlap.Click
        lblError.Visible = False
        If (Not txtReden.Text = String.Empty) Then
            bot.Actions.Slap(userInfo(0), txtActiePers.Text)
        Else
            lblError.Visible = True
        End If
    End Sub

    Protected Sub btnAdmin_Click(sender As Object, e As EventArgs) Handles btnAdmin.Click
        bot.Dispose()
        Response.Redirect("Admin.aspx")
    End Sub

    Protected Sub btnLogOff_Click(sender As Object, e As EventArgs) Handles btnLogOff.Click
        updateOutput("", "?¿ Logging Off ¿?")
        Session.RemoveAll()
        bot.Dispose()
        Response.Redirect("Login.aspx")
    End Sub
End Class